/**
 * 版权所有(C) COVISINT 2015-2025
 * Copyright 2015-2025 COVISINT
 * 创建日期：Jun 26, 20175:42:42 PM
 * 创建人：yyang
 */
package com.wechat.framework.utils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.wechat.framework.messages.resp.ArticleResp;
import com.wechat.framework.messages.resp.ImageRespMessages;
import com.wechat.framework.messages.resp.NewsRespMessages;
import com.wechat.framework.messages.resp.TextRespMessages;
import com.wechat.framework.messages.resp.VideoRespMessages;
import com.wechat.framework.messages.resp.VoiceRespMessages;

public class WechatMessageUtils {
	
	/**
	 * 文本消息对象转换成xml
	 * @param textMessage 文本消息对象
	 * @return xml
	 */
	public static String textRespMessageToXml(TextRespMessages textMessage) {
		xstream.alias("xml", textMessage.getClass());
		return xstream.toXML(textMessage);
	}
	
	/**
	 * 图片消息对象转换成xml
	 * @param imageMessage 文本消息对象
	 * @return xml
	 */
	public static String imageRespMessageToXml(ImageRespMessages imageMessage) {
		xstream.alias("xml", imageMessage.getClass());
		return xstream.toXML(imageMessage);
	}
	
	/**
	 * 语音消息对象转换成xml
	 * @param voiceMessage 语音消息对象
	 * @return xml
	 */
	public static String voiceRespMessageToXml(VoiceRespMessages voiceMessage) {
		xstream.alias("xml", voiceMessage.getClass());
		return xstream.toXML(voiceMessage);
	}
	
	/**
	 * 视频消息对象转换成xml
	 * @param videoMessage 视频消息对象
	 * @return xml
	 */
	public static String videoRespMessageToXml(VideoRespMessages videoMessage) {
		xstream.alias("xml", videoMessage.getClass());
		return xstream.toXML(videoMessage);
	}
	
	/**
	 * 图文消息对象转换成xml
	 * @param newsMessage 图文消息对象
	 * @return xml
	 */
	public static String newsMessageToXml(NewsRespMessages newsMessage) {
		xstream.alias("xml", newsMessage.getClass());
		xstream.alias("item", new ArticleResp().getClass());
		return xstream.toXML(newsMessage);
	}
	
	/**
	 * 扩展xstream，使其支持CDATA块
	 */
	private static XStream xstream = new XStream(new XppDriver() {
		public HierarchicalStreamWriter createWriter(Writer out) {
			return new PrettyPrintWriter(out) {
				// 对所有xml节点的转换都增加CDATA标记
				boolean cdata = true;

				@SuppressWarnings("rawtypes")
				public void startNode(String name, Class clazz) {
					super.startNode(name, clazz);
				}

				protected void writeText(QuickWriter writer, String text) {
					if (cdata) {
						writer.write("<![CDATA[");
						writer.write(text);
						writer.write("]]>");
					} else {
						writer.write(text);
					}
				}
			};
		}
	});

	/**
	 * 解析微信发来的请求（XML）
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public static Map<String, String> parseXml(String request) throws Exception {
		
		//将解析结果存储在HashMap中
		Map<String, String> resultMap = new HashMap<String, String>();
		
		//从request中取得输入流 
		InputStream inputStream = new ByteArrayInputStream(request.getBytes("UTF-8"));
		
		//读取输入流 
		SAXReader reader = new SAXReader();
		Document document = reader.read(inputStream);

		//得到根元素的所有子节点
		@SuppressWarnings("unchecked")
		List<Element> elementList = document.getRootElement().elements();
		
		//遍历所有子节点
		getElements(elementList,resultMap);
		
		//释放资源 
		inputStream.close();
		inputStream = null;
		return resultMap;
	}	

	@SuppressWarnings("unchecked")
	private static void getElements(List<Element> elementList,Map<String, String> resultMap) {
		//采用递归方式取得所有XML节点名及其Value
		Iterator<Element> iterator = elementList.iterator();
		while (iterator.hasNext()) {
			Element element = (Element) iterator.next();
			if (element.elements().size() > 0) {
				getElements(element.elements(), resultMap);
			} else {
				resultMap.put(element.getName(), element.getText());
			}
		}
	}
}
